package com.repro.lib_base.bases.activity

import android.annotation.SuppressLint
import android.content.res.Resources
import android.os.Build
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.repro.com.repro.lib_base.R
import com.repro.lib_base.utils.ClickUtil
import com.repro.lib_base.utils.SoftInputUtil

/**
 *使用系统toolbar的时候需要设置主体样式为NoTitle否则会出现错误
 * <item name="windowActionBar">false</item> 关闭actionbar
 * <item name="windowNoTitle">true</item>    关闭title
 */
open class ToolBarView internal constructor(builder: Builder) {
    private var mToolbar: Toolbar? = null
    private var mTitle: TextView? = null
    private lateinit var res: Resources

    //创建toolbar
    fun onCreateToolBar(layoutInflater: LayoutInflater, context: AppCompatActivity): Toolbar? {
        res = context.resources
        val resourceId = if (isCenterTitleInToolbars) {
            R.layout.base_toolbar_center
        } else {
            R.layout.base_toolbar_normal
        }
        mToolbar = layoutInflater.inflate(resourceId, null) as Toolbar

        if (isCenterTitleInToolbars) {
            mTitle = mToolbar?.findViewById(R.id.toolbar_title_tv)
        }

        toolbarSetting(context)
        return mToolbar
    }

    /**
     * toolbar设置
     * 标题title,size,textColor
     * Toolbar的setTitle方法要在setSupportActionBar(toolbar)之前调用，否则不起作用
     *
     * 当设置title中间显示之后 需要自己设置颜色，大小
     * 当不设置中间显示title的时候则使用过的是系统toolbar 只需要设置颜色，内容
     */
    @SuppressLint("UseCompatLoadingForDrawables", "ClickableViewAccessibility")
    private fun toolbarSetting(context: AppCompatActivity) {
        mToolbar.let { toolBar ->
            //设置标题
            titleString.let {
                if (it.isNotEmpty()) {
                    if (isCenterTitleInToolbars) {
                        mTitle?.text = it
                        isShowToolbarTitlesIsEnable = false
                    } else {
                        mToolbar?.title = it
                        isShowToolbarTitlesIsEnable = true
                    }
                }
            }

            //设置颜色
            titleColor.let {
                if (isCenterTitleInToolbars) {
                    mTitle?.setTextColor(res.getColor(it))
                } else {
                    mToolbar?.setTitleTextColor(it)
                }
            }

            //设置字体大小，
            titleSize.let {
                if (isCenterTitleInToolbars) {
                    mTitle?.textSize = it
                }
            }

            //设置副标题 只有使用默认的toolbar的时候才可以使用副标题
            subTitleString.let {
                if (it.isNotEmpty() && !isCenterTitleInToolbars) {
                    toolBar?.subtitle = it
                    isShowToolbarTitlesIsEnable = true
                }
            }

            //设置toolbar背景
            toolbarBgColor.let {
                if (it > 0) {
                    try {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                            toolBar?.background = context.getDrawable(it)
                        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            toolBar?.background = res.getDrawable(it)
                        }
                    } catch (e: Resources.NotFoundException) {

                    }
                }
            }

            context.setSupportActionBar(toolBar)

            val mActionBar = context.supportActionBar
            //修改导航按钮
            resNavigationIcon.let {
                if (it > 0) {
                    mActionBar?.setHomeAsUpIndicator(it)
                }
            }

            //显示返回按钮
            mActionBar?.setDisplayHomeAsUpEnabled(isShowHomeAsUps) // 给左上角图标的左边加上一个返回的图标
            //可响应返回键点击事件
            mActionBar?.setDisplayShowHomeEnabled(true) //使左上角图标是否显示，如果设成false，则没有程序图标，仅仅就个标题，否则，显示应用程序图标，对应id为android.R.id.home
            //返回键ICON
            mActionBar?.setDisplayShowCustomEnabled(true)//使自定义的普通View能在title栏显示，
            //设置是否展示title
            mActionBar?.setDisplayShowTitleEnabled(isShowToolbarTitlesIsEnable)//对应ActionBar.DISPLAY_SHOW_TITLE。

            //点击的时候关闭软件盘
            toolBar?.setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_DOWN) {
                    SoftInputUtil.hideSoftInputView(context)
                }
                false
            }

            //点击菜单栏的按键监听
            listener.let {
                if (it == null) {
                    //点击菜单栏的返回按钮
                    toolBar?.setOnMenuItemClickListener { item ->
                        when (item.itemId) {
                            android.R.id.home -> {//左侧返回按钮
                                context.onBackPressed()
                                true
                            }
                            else -> {
                                false
                            }
                        }
                    }
                } else {
                    toolBar?.setOnMenuItemClickListener(it)
                }
            }

            //返回按钮事件响应
            toolBar?.setNavigationOnClickListener {
                if (ClickUtil.isClickAvailable()) {
                    context.onBackPressed()
                }
            }
        }
    }

    /**
     * toolbar menu菜单栏
     */
    internal fun onCreateMenuView(context: AppCompatActivity, menuItem: Menu?) {
        resMenuId.let {
            if (it > 0) {
                context.menuInflater.inflate(resMenuId, menuItem)
            }
        }
    }

    /**
     * 设置toolbar的topMargin为statusBarHeight
     * toolbar偏移量
     */
    private fun toolbarTopMarginStatusBar(mToolbar: Toolbar?): FrameLayout.LayoutParams {
        val layoutParams = mToolbar?.layoutParams as FrameLayout.LayoutParams
        layoutParams.topMargin = getStatusBarHeight()
        mToolbar.layoutParams = layoutParams
        return layoutParams
    }

    /**
     * 内容区域是否 margin to top
     * @ToolbarMode.Layer 同级关系模式则需要 topMargin
     * @ToolbarMode.Parallel 上下级关系模式则不需要Margin 如沉浸模式
     * FrameMarginParams topMargin statusBarHeight+ToolbarHeight
     */
    fun contentTopMarginLayoutParams(isEnableFitSystemWindows: Boolean): FrameLayout.LayoutParams {
        val mode = toolbarMode
        val contentViewLayoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        if (mode == ToolbarMode.Layer) {
            contentViewLayoutParams.topMargin = getToolbarHeightSpan()
        } else {
            //当出现上下叠加的时候如果需要toolbar 则自动marginTop
            if (!isEnableFitSystemWindows) {
                toolbarTopMarginStatusBar(mToolbar)
            }
        }
        return contentViewLayoutParams
    }


    /**
     * toolbar高度
     */
    fun getToolbarHeightSpan(): Int {
        return res.getDimensionPixelOffset(R.dimen.dimen_dp_56)
    }

    /**
     * statusBarHeight高度
     */
    private fun getStatusBarHeight(): Int {
        //获取系统statusBar高度
        val toolbarResID: Int =
            res.getIdentifier("status_bar_height", "dimen", "android")
        return if (toolbarResID > 0) {
            res.getDimensionPixelOffset(toolbarResID)
        } else {
            0
        }
    }


    internal var isShowToolbarTitlesIsEnable: Boolean = false//是否展示系统标题栏
    internal var isCenterTitleInToolbars: Boolean = true//是否居中展示title
    internal var toolbarMode: Int = ToolbarMode.Parallel//设置toolbar和content层叠模式
    internal var isShowHomeAsUps: Boolean = true//是否展示返回按钮
    internal var resNavigationIcon: Int = 0//修复返回按钮图标
    internal var titleString: String = ""//标题
    internal var titleSize: Float = 20f//颜色
    internal var titleColor: Int = R.color.color_191919//背景颜色
    internal var subTitleString: String = ""//副标题
    internal var toolbarBgColor: Int = 0//toolbar背景颜色
    internal var resMenuId: Int = 0
    internal var listener: Toolbar.OnMenuItemClickListener? = null

    constructor() : this(Builder())

    init {
        this.isCenterTitleInToolbars = builder.isCenterTitleInToolbars
        this.toolbarMode = builder.toolbarMode
        this.isShowHomeAsUps = builder.isShowHomeAsUps
        this.resNavigationIcon = builder.resNavigationIcon
        this.titleString = builder.titleString
        this.titleSize = builder.titleSize
        this.titleColor = builder.titleColor
        this.subTitleString = builder.subTitleString
        this.toolbarBgColor = builder.toolbarBgColor
        this.resMenuId = builder.resMenuId
        this.listener = builder.listener
    }


    class Builder constructor() {
        var isCenterTitleInToolbars: Boolean = true//是否居中展示title
        var toolbarMode: Int = ToolbarMode.Layer//设置toolbar和content层叠模式
        var isShowHomeAsUps: Boolean = true//是否展示返回按钮
        var resNavigationIcon: Int = 0//修复返回按钮图标
        var titleString: String = ""//标题
        var titleSize: Float = 20f//颜色
        var titleColor: Int = R.color.color_191919//背景颜色
        var subTitleString: String = ""//副标题
        var toolbarBgColor: Int = 0//toolbar背景颜色
        var resMenuId: Int = 0//toolbar背景颜色
        var listener: Toolbar.OnMenuItemClickListener? = null

        /**
         * 是否展示中心标题
         * @param isCenterTitle 默认true title中间展示
         */
        fun setIsCenterTitleInToolbar(isCenterTitle: Boolean) = apply {
            this.isCenterTitleInToolbars = isCenterTitle
        }

        /**
         * toolbar 层叠模式
         * @param toolbarMode ToolbarMode.Parallel 上下层叠关系
         *       默认   ToolbarMode.Layer 同级关系
         *
         */
        @SuppressLint("SupportAnnotationUsage")
        @ToolbarMode
        fun setRequestToolbarMode(toolbarMode: Int) = apply {
            this.toolbarMode = toolbarMode
        }

        /**
         * 是否展示返回按钮
         * @param isEnable 默认true 展示
         */
        fun setIsShowHomeAsUp(isEnable: Boolean) = apply {
            this.isShowHomeAsUps = isEnable
        }

        /**
         * 修改返回按钮的图片
         * @param resId 资源id 需要配合@isShowHomeAsUp = true 才可以展示否则无效
         */
        fun setRequestNavigationIcon(@DrawableRes resId: Int) = apply {
            this.resNavigationIcon = resId
        }

        /**
         * 标题
         * @param res title标题内容默认""
         */
        fun setRequestTitle(@SuppressLint("SupportAnnotationUsage") @StringRes res: String) = apply {
                this.titleString = res
            }

        /**
         * 标题字体大小
         * @param size 默认20f也可以根据需求调整
         */
        fun setRequestTitleSize(size: Float) = apply {
            this.titleSize = size
        }

        /**
         * 设置标题颜色
         * @param colorInt 默认R.color.color_191919
         */
        fun setRequestTitleColor(@DrawableRes colorInt: Int) = apply {
            this.titleColor = colorInt
        }

        /**
         * 设置副标题
         * @param subtitle 副标题内容
         *          副标题需要设置isCenterTitleInToolbar(false)才可以展示
         */
        fun setRequestSubTitleInToolbar(subtitle: String) = apply {
            this.subTitleString = subtitle
        }

        /**
         * 设置toolbar背景颜色
         * @param toolbarBgColor R.color.w
         */
        fun setRequestToolbarBg(toolbarBgColor: Int) = apply {
            this.toolbarBgColor = toolbarBgColor
        }

        /**
         * toolbar menu 右侧菜单栏
         * @param resMenuId 资源id
         */
        fun setRequestMenuId(resMenuId: Int) = apply {
            this.resMenuId = resMenuId
        }

        /**
         * 菜单栏设置监听器
         */
        fun setOnMenuItemClickListener(listener: Toolbar.OnMenuItemClickListener) = apply {
            this.listener = listener
        }


        override fun toString(): String {
            return "Builder(isCenterTitleInToolbars=$isCenterTitleInToolbars, " +
                    "toolbarMode=$toolbarMode, " +
                    "isShowHomeAsUps=$isShowHomeAsUps, " +
                    "resNavigationIcon=$resNavigationIcon, " +
                    "titleString='$titleString', " +
                    "titleSize=$titleSize, " +
                    "titleColor=$titleColor, " +
                    "subTitleString='$subTitleString', " +
                    "toolbarBgColor=$toolbarBgColor，)"
        }

        fun build(): ToolBarView {
            return ToolBarView(this)
        }
    }
}